package br.edu.planodesaude.GUI.medico;

import java.util.ArrayList;

import javax.swing.DefaultListModel;
import javax.swing.JDesktopPane;
import javax.swing.JOptionPane;

import br.edu.planodesaude.controle.Alteradora;
import br.edu.planodesaude.controle.Pesquisadora;
import br.edu.planodesaude.dominio.Especialidade;
import br.edu.planodesaude.dominio.Medico;
import br.edu.planodesaude.exceptions.SearchException;
import br.edu.planodesaude.exceptions.UpdateException;

public class AtualizarMedico extends javax.swing.JInternalFrame {

    /**
     * Creates new form AtualizarMedico
     */
	
	private static DefaultListModel model = new DefaultListModel();
	
	private static void initAdd(){
		model.clear();
		
		try {
			ArrayList<Especialidade> esp = new Pesquisadora().getEspecialidades();
			
			for(Especialidade especialidade : esp){
				model.addElement(especialidade);
			}
			
		} catch (SearchException e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), "Informação", JOptionPane.INFORMATION_MESSAGE);
		}
        
        espAddJList1.setModel(model);
	}
	
	private void initRemove(ArrayList<Especialidade> especialidades){	
		System.out.println(this.getBounds().toString());
		DefaultListModel modelRemove = new DefaultListModel();
		
		modelRemove.clear();
		
		for(Especialidade especialidade : especialidades){
			modelRemove.addElement(especialidade);
		}
	        
	    espRemoveJList.setModel(modelRemove);
	}
	
	
    public AtualizarMedico() {
    	initComponents();
    	setClosable(true);
    	setVisible(true);
    	setTitle("Alterar Médico");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        especialidadesJList = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        crmJTextField = new javax.swing.JTextField();
        buscarJButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        nomeJTextField = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        espAddJList1 = new javax.swing.JList();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        espRemoveJList = new javax.swing.JList();
        removeJButton = new javax.swing.JButton();
        vinculaJButton = new javax.swing.JButton();
        cadastraJButton = new javax.swing.JButton();

        especialidadesJList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        especialidadesJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(especialidadesJList);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("CRM");

        buscarJButton.setText("Buscar");
        buscarJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buscarJButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("Nome");

        jLabel3.setText("Especialidade(s) Vinculada(s)");

        espAddJList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = {};
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        espAddJList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(espAddJList1);

        jLabel4.setText("Especialidade(s)");

        espRemoveJList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        espRemoveJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane3.setViewportView(espRemoveJList);

        removeJButton.setText("Remover");
        removeJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeJButtonActionPerformed(evt);
            }
        });

        vinculaJButton.setText("Vincular");
        vinculaJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                vinculaJButtonActionPerformed(evt);
            }
        });

        cadastraJButton.setText("Alterar");
        cadastraJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cadastraJButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel4)
                            .addComponent(jScrollPane2)
                            .addComponent(vinculaJButton, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(removeJButton, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(crmJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(buscarJButton, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(nomeJTextField))))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
            .addGroup(layout.createSequentialGroup()
                .addGap(181, 181, 181)
                .addComponent(cadastraJButton, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(crmJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(buscarJButton))
                            .addComponent(jLabel1))
                        .addGap(41, 41, 41)
                        .addComponent(jLabel2))
                    .addComponent(nomeJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(removeJButton)
                    .addComponent(vinculaJButton))
                .addGap(18, 18, 18)
                .addComponent(cadastraJButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        setBounds(429, 155, 500, 415);
    }// </editor-fold>                        

Medico medico = null;
    
    private void buscarJButtonActionPerformed(java.awt.event.ActionEvent evt) {
    
    	if(crmJTextField.getText().equals("")){
        	JOptionPane.showMessageDialog(null, "Informe o CRM", "Aviso", JOptionPane.INFORMATION_MESSAGE);
        }else{
        	try{
        		medico = new Pesquisadora().pesquisarMedico(crmJTextField.getText());
        		crmJTextField.setEditable(false);
        		nomeJTextField.setText(medico.getNome());
        		initRemove(medico.getEspecialidades());
        		initAdd();
        	}catch(SearchException sex){
        		JOptionPane.showMessageDialog(null, sex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
        	}
        }
    }                                             

    private void removeJButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              
        if(medico == null){
        	JOptionPane.showMessageDialog(null, "Informe o CRM", "Aviso", JOptionPane.INFORMATION_MESSAGE);
        }else if(espRemoveJList.getSelectedValue() == null){
        	JOptionPane.showMessageDialog(null, "Selecione uma especialidade", "Aviso", JOptionPane.INFORMATION_MESSAGE);
        }else{
        	Especialidade esp = (Especialidade)espRemoveJList.getSelectedValue();
        	
        	for(int i = 0; i < medico.getEspecialidades().size(); i++){
        		if(medico.getEspecialidades().get(i).equals(esp)){
        			medico.getEspecialidades().remove(i);
        			break;
        		}
        	}
        	
        	initRemove(medico.getEspecialidades());
        }
    }                                             

    private void vinculaJButtonActionPerformed(java.awt.event.ActionEvent evt) {                                               
    	if(medico == null){
        	JOptionPane.showMessageDialog(null, "Informe o CRM", "Aviso", JOptionPane.INFORMATION_MESSAGE);
        }else{
        	Especialidade esp = (Especialidade)espAddJList1.getSelectedValue();
        	
        	boolean ok = true;
        	
        	for(Especialidade espes : medico.getEspecialidades()){
        		if(espes.equals(esp)){
        			JOptionPane.showMessageDialog(null, "Especialidade já vinculada", "Aviso", JOptionPane.INFORMATION_MESSAGE);
        			ok = false;
        			break;
        		}
        	}
        	
        	if(ok){
        		medico.getEspecialidades().add(esp);
        		initRemove(medico.getEspecialidades());
        	}
        }
    }                                               

    private void cadastraJButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                
    	if(medico == null){
        	JOptionPane.showMessageDialog(null, "Informe o CRM", "Aviso", JOptionPane.INFORMATION_MESSAGE);
    	}else if(medico.getEspecialidades().isEmpty()){
    		JOptionPane.showMessageDialog(null, "O médico deve ter ao menos uma especialidade!", "Aviso", JOptionPane.INFORMATION_MESSAGE);
    	}else{
			try{
		    	new Alteradora().alterarMedico(crmJTextField.getText(), nomeJTextField.getText(), medico.getEspecialidades(), true);
		    	JOptionPane.showMessageDialog(null, "Alteração Realizada com sucesso!", "Sucesso", JOptionPane.INFORMATION_MESSAGE);
		    	dispose();
		    } catch(UpdateException uex){
		    	JOptionPane.showMessageDialog(null, uex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
		    }
    	}
    }                                               

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AtualizarMedico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AtualizarMedico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AtualizarMedico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AtualizarMedico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AtualizarMedico();
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton buscarJButton;
    private javax.swing.JButton cadastraJButton;
    private javax.swing.JTextField crmJTextField;
    private static javax.swing.JList espAddJList1;
    private javax.swing.JList espRemoveJList;
    private javax.swing.JList especialidadesJList;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextField nomeJTextField;
    private javax.swing.JButton removeJButton;
    private javax.swing.JButton vinculaJButton;
    // End of variables declaration                   
}

